import {createRouter, createWebHashHistory, RouteRecordRaw} from "vue-router"
import routerList from '@/router/index.ts'
import {processRequest, token} from "@/framework"
import {FRAME_APIS} from "@/frame/apis"
import {useSystemStore} from "@/store/system";
import APIS from "@/apis";

/**
 * 路由
 */
const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        name: "login",
        component: () => import("@/frame/pages/login/index.vue"),
        meta: {
            title: "登录"
        }
    },
    {
        path: "/index",
        name: "index",
        component: () => import("@/frame/pages/index/index.vue"),
        meta: {
            title: "首页"
        },
        redirect: "/code-rule",
        children: routerList
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

/**
 * 白名单
 */
const whiteRouterList = ["/login"]

/**
 * 路由守卫
 */
router.beforeEach(async (to, from, next) => {
    //检验白名单
    if (whiteRouterList.includes(to.path)) {
        next()
        return
    }

    const tokenValue = token.get()

    //校验
    if (!tokenValue) {
        //无token，跳转登录页
        next("/login")
        return
    } else {
        const systemStore = useSystemStore()

        if (!systemStore.userData) {
            const userData = await processRequest.get(FRAME_APIS.LOGIN_BASE_GET_USER_DETAIL)
            systemStore.updateUserData(userData)

            if (!systemStore.menuList) {
                const menuList = await processRequest.get(APIS.MENU_BASE_USER)
                systemStore.updateMenuList(menuList)
            }
        }
        if (to.path === "/") {
            next("/index")
        }
        next()
    }
})

export default router
